/*******************************************************************************
 * Copyright (c) 2010 Sylvain Sicard.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Sylvain Sicard - initial API and implementation
 ******************************************************************************/
package com.googlecode.ssdutils.jlauncher;

import java.lang.reflect.Field;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;

import com.googlecode.ssdutils.jlauncher.annotations.Option;

/**
 * @author Sylvain Sicard
 * 
 */
public class OptionsFactory {

	/**
	 * @param options
	 * @param launchConfiguration
	 */
	public void buildOptions(Options options,
			LaunchConfiguration launchConfiguration) {

		for (Field optionField : launchConfiguration.getOptions()) {
			Option option = optionField.getAnnotation(Option.class);
			options.addOption(OptionBuilder.withArgName(option.name()).hasArg()
					.withDescription(option.help()).create(option.name()));
		}
	}

	/**
	 * @param launchConfiguration
	 * @param line
	 * @return
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 */
	public boolean initAndValidate(LaunchConfiguration launchConfiguration,
			CommandLine line) throws IllegalArgumentException,
			IllegalAccessException {
		boolean isValide = true;
		for (Field f : launchConfiguration.getOptions()) {
			Option option = f.getAnnotation(Option.class);
			if (line.hasOption(option.name())) {
				launchConfiguration.setOptionValue(f,
						line.getOptionValue(option.name()));
			} else if (!option.optional()) {
				isValide = false;
				break;
			}
		}
		return isValide;
	}

}
